package com.labichaoka.chaoka.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.labichaoka.chaoka.BuildConfig;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.MyApplication;
import com.labichaoka.chaoka.widget.MyProgressBar;
import com.tbruyelle.rxpermissions.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 更新管理
 * Created by 14658 on 2016/7/4.
 */
public class UpdateManager {
    /* 下载包安装路径 */
    private static final String savePath = "/sdcard/superCard/";
    private static final String saveFileName = savePath + "superCard.apk";
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private final int UPDATE_ERROR = 3;
    private final int CHECK_PROGRESS_TIME = 8000;
    private Context mContext;
    private String apkUrl;//下载路径
    private String explain;//下载说明
    private boolean upgradeType;//下载类型(0为非强制升级，1为强制升级)
    private Dialog noticeDialog;//通知升级窗口
    private Dialog downloadDialog;//升级窗口
    private Dialog dialog;
    private WeakReference<Activity> weakReference;
    /* 进度条与通知ui刷新的handler和msg常量 */
    //private ProgressBar mProgress;
    private int progress;
    private boolean interceptFlag = false;
    private Timer errorTimer;
    private int lastCount = 0;
    private MyProgressBar myProgressBar;

//    private Handler mHandler = new Handler() {
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case DOWN_UPDATE:
//                    myProgressBar.setProgress(progress);
//                    break;
//                case DOWN_OVER:
//                    installApk();
//                    break;
//                case UPDATE_ERROR:
//                    //十秒进度无变化的操作
//                    ToastUtils.show("下载速度过慢，请耐心等待");
//                    break;
//                default:
//                    break;
//            }
//        }
//    };

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    myProgressBar.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installApk();
                    break;
                case UPDATE_ERROR:
                    //十秒进度无变化的操作
                    ToastUtils.show("下载速度过慢，请耐心等待");
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    /**
     * 禁用点击返回按钮事件
     */
    private DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            return keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0;
        }
    };
    private Runnable mdownApkRunnable = new Runnable() {
        int count = 0;

        @Override
        public void run() {
            try {
                TimerTask timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if (lastCount == count) {
                            mHandler.sendEmptyMessage(UPDATE_ERROR);
                        } else {
                            lastCount = count;
                        }
                    }
                };
                errorTimer = new Timer(true);
                errorTimer.schedule(timerTask, CHECK_PROGRESS_TIME, CHECK_PROGRESS_TIME);
                URL url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (file.exists()) {
                    file.delete();
                }
                file.mkdir();
                File ApkFile = new File(saveFileName);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                do {
                    byte buf[] = new byte[1024];
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);//点击取消就停止下载.
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    public UpdateManager(Activity act, Context context, String apkUrl, String explain, boolean upgradeType) {
        weakReference = new WeakReference<>(act);
        this.mContext = context;
        this.apkUrl = apkUrl;
        this.explain = explain;
        this.upgradeType = upgradeType;
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
    }

    //外部接口让主Activity调用
    public void checkUpdateInfo() {
        showDialog(explain, upgradeType);
    }

    private void showDialog(String explain, final boolean updateType) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.check_update_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        TextView doDownload = (TextView) v.findViewById(R.id.ok);
        TextView cancel = (TextView) v.findViewById(R.id.cancel);
        final View v1 = (View) v.findViewById(R.id.view1);
        final LinearLayout ly = (LinearLayout) v.findViewById(R.id.lyBottom);
        final TextView topText = (TextView) v.findViewById(R.id.topeText);
        final TextView updateContent = (TextView) v.findViewById(R.id.updateContent);
        myProgressBar = (MyProgressBar) v.findViewById(R.id.pb);
        final MyProgressBar pb = myProgressBar;

        final RxPermissions rxPermissions = new RxPermissions(weakReference.get());
        //先判断更新类型
        if (updateType) {
            //强制升级
            cancel.setText("退出");
        } else {
            //非强制更新
            cancel.setText("取消");
        }
        updateContent.setText(explain);

        doDownload.setOnClickListener((view) -> {

            rxPermissions.request(Manifest.permission
                    .WRITE_EXTERNAL_STORAGE).subscribe(
                    granted -> {
                        if (granted) {
                            pb.setVisibility(View.VISIBLE);
                            ly.setVisibility(View.GONE);
                            v1.setVisibility(View.GONE);
                            topText.setText("版本更新中...");
                            updateContent.setVisibility(View.GONE);
                            downloadApk();
                        } else {
                            boolean storageGranted = ActivityCompat.checkSelfPermission(mContext,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager
                                    .PERMISSION_GRANTED;
                            if (!storageGranted) {
                                ToastUtils.show("无法访问本地存储");
                            } else {
                                throw new IllegalStateException("here is never reach.");
                            }
                        }
                    }
            );


        });

        cancel.setOnClickListener((view) -> {
            if (updateType) {
                dialog.dismiss();
                MyApplication.appExit();
                android.os.Process.killProcess(android.os.Process.myPid());//获取PID
                System.exit(0);//退出当前应用
            } else {
                dialog.dismiss();
                EventBus.getDefault().post(1);


            }
            interceptFlag = true;
        });

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0;
            }
        });
        dialog.show();
        //dialog.setCancelable(false);
    }


    /**
     * 下载apk
     */
    private void downloadApk() {
        Thread downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File outputFile = new File(saveFileName);
            if (!outputFile.exists()) {
                return;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                boolean installAllowed;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //兼容8.0
                    installAllowed = mContext.getPackageManager().canRequestPackageInstalls();
                    if (installAllowed) {
                        Uri contentUri = FileProvider.getUriForFile(mContext,
                                BuildConfig.APPLICATION_ID + ".path", outputFile);

                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        Intent intent2 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mContext.getPackageName()));
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent2);
                        Uri contentUri = FileProvider.getUriForFile(mContext,
                                BuildConfig.APPLICATION_ID + ".path", outputFile);

                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    }
                } else {
                    Uri contentUri = FileProvider.getUriForFile(mContext,
                            BuildConfig.APPLICATION_ID + ".path", outputFile);

                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                }

            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
            }
            mContext.startActivity(intent);
            System.exit(0);

        } else {
            ToastUtils.show("请确认插入SD卡");
        }

    }
}
